<template>
    <div class="page-content">
        <div class="header">
            <h3>基础设置</h3>
        </div>
        <el-form label-width="120px" :model="formData" :rules="rules" ref="ruleFormRef">
            <el-form-item label="活动类型">
                <div class="tips">新人礼包</div>
            </el-form-item>
            <el-form-item label="活动名称" prop="activityName">
                <el-input v-model="formData.activityName" placeholder="请输入活动名称"></el-input>
            </el-form-item>
            <el-form-item label="活动时间" prop="activeTime">
                <el-date-picker label="活动时间：" v-model="formData.activeTime" type="datetimerange"
                    start-placeholder="开始日期" end-placeholder="结束日期" @change="timeChange"
                    :disabled-date="disabledDate" />
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input v-model="formData.title" maxlength="12" show-word-limit placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="副标题" prop="subtitle">
                <el-input v-model="formData.subtitle" maxlength="16" show-word-limit placeholder="请输入副标题"></el-input>
            </el-form-item>
            <el-form-item label="领取弹窗背景图">
                <el-input v-model="formData.shareImage" style="display: none"></el-input>
                <div class="avatar-uploader" @click="openImageDialog('shareImage')">
                    <el-image v-if="formData.shareImage" :src="formData.shareImage" class="avatar"
                        fit="contain"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                            <Plus />
                        </el-icon></i>
                    <div v-if="formData.shareImage" class="mask">替换</div>
                    <el-icon v-if="formData.shareImage" class="del-image" :size="20"
                        @click.stop="handleDelImg('shareImage')">
                        <CircleCloseFilled />
                    </el-icon>
                </div>
            </el-form-item>
            <el-form-item label="领取完成背景图">
                <el-input v-model="formData.receiveSuccessImage" style="display: none"></el-input>
                <div class="avatar-uploader" @click="openImageDialog('receiveSuccessImage')">
                    <el-image v-if="formData.receiveSuccessImage" :src="formData.receiveSuccessImage" class="avatar"
                        fit="contain"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                            <Plus />
                        </el-icon></i>
                    <div v-if="formData.receiveSuccessImage" class="mask">替换</div>
                    <el-icon v-if="formData.receiveSuccessImage" class="del-image" :size="20"
                        @click.stop="handleDelImg('receiveSuccessImage')">
                        <CircleCloseFilled />
                    </el-icon>
                </div>
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
                <el-switch v-model="formData.status" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
        </el-form>
        <div class="header">
            <h3>活动规则</h3>
        </div>
        <el-form label-width="100px" :model="formData" :rules="rules" ref="ruleFormRef">
            <el-form-item label="活动对象">
                <div>
                    <div class="tips">活动时间内注册的新用户</div>
                    <div class="coutomTips">未注册用户进入首页时，弹窗展示该礼包，注册成功后立即发放礼包</div>
                </div>
            </el-form-item>
            <el-form-item label="活动赠送">
                <el-checkbox-group v-model="formData.giftType" disabled>
                    <el-checkbox value="1">赠送会员Vip</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="选择vip" v-if="formData.giftType && formData.giftType.includes('1')" prop="giftRefIds">
                <el-select v-model="formData.giftRefIds" multiple placeholder="请选择VIP">
                    <el-option :label="item.name" :value="item.id" v-for="(item, index) in vipData" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <!-- <el-button type="primary" style="width: 90px" v-if="!isEdit" @click="edit">
                    编辑
                </el-button> -->
                <el-button type="primary" style="width: 90px" @click="handleSave" :loading="btnLoding">
                    保存
                </el-button>
                <el-button type="default" @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
        <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
            :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
            :operationType="false"></image-selected-dialog>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import { addActive, getActivityInfo, editActive } from '@/api/marketing'
import { vipEquity } from '@/api/userStudentsApi'
import { useRoute } from 'vue-router'

const route = useRoute()

const formData = reactive({
    activityName: '',
    activeTime: ['', ''],
    startTime: '',
    endTime: '',
    shareImage: '',
    giftType: ['1'],
    giftRefIds: [],
    status: 1,
    title: '',
    subtitle: '',
    receiveSuccessImage: ''
})

const router = useRouter()
const isEdit = ref(false)
const btnLoding = ref(false)

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
    activeTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
    giftRefIds: [
        {
            required: true,
            type: 'array',
            min: 1,
            message: '请选择vip',
            trigger: ['change', 'blur']
        }
    ],
    // title: [{ required: true, message: '请输入标题', trigger: 'change' }],
    // subtitle: [{ required: true, message: '请输入副标题', trigger: 'change' },]
})
const timeChange = (e: any) => {
    formData.startTime = e[0]
    formData.endTime = e[1]
}

// 禁止选择今天之前的时间（包括今天0点前）
const disabledDate = (date: Date) => {
    // 禁用今天0点之前的时间
    const now = new Date()
    // 去除秒毫秒，保证对比一致
    const nowWithoutMs = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    // date-picker传进来的date是本地时区的凌晨0点
    return date < nowWithoutMs
}

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const vipData = ref<any>([])
const currentImageType = ref('') // 当前操作的图片类型

const openImageDialog = (imageType: string) => {
    currentImageType.value = imageType
    showImageChooseDialog.value = true
}

const handleCloseImageDialog = (value: any) => {
    if (value && value.fileUrl) {
        if (currentImageType.value === 'shareImage') {
            formData.shareImage = value.fileUrl
        } else if (currentImageType.value === 'receiveSuccessImage') {
            formData.receiveSuccessImage = value.fileUrl
        }
    }
    showImageChooseDialog.value = false
    currentImageType.value = ''
}

const handleDelImg = (imageType: string) => {
    if (imageType === 'shareImage') {
        formData.shareImage = ''
    } else if (imageType === 'receiveSuccessImage') {
        formData.receiveSuccessImage = ''
    }
}

const edit = () => {
    isEdit.value = !isEdit.value
}

const formatDate = (date: string) => {
    return new Date(date)
        .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
        .replace(/\//g, '-')
}

const editId = ref('')

const handleSave = () => {
    // 校验表单 必须有 vip
    ruleFormRef.value?.validate((valid: boolean) => {
        if (valid) {
            isEdit.value = !isEdit.value
            if (editId.value) {
                editHandle()
            } else {
                addHandle()
            }
        }
    })
}

function goBack() {
    router.push('/result/newCustomVip')
}

const buildActivityObj = () => {
    const obj: any = {
        activityName: formData.activityName,
        shareImage: formData.shareImage,
        startTime: formData.startTime ? formatDate(formData.startTime) : '',
        endTime: formData.endTime ? formatDate(formData.endTime) : '',
        activityType: '02',
        status: formData.status,
        title: formData.title,
        subtitle: formData.subtitle,
        receiveSuccessImage: formData.receiveSuccessImage,
        activityContentVoList: [{
            targetType: '01',
            giftType: '04',
            giftRefIds: formData.giftRefIds.length ? formData.giftRefIds.join(',') : '',
            giftQuantity: 1,
            limitPerUser: 1
        }]
    }
    return obj
}

const addHandle = async () => {
    try {
        const res = await addActive(buildActivityObj())
        if (res.code === '00000') {
            ElMessage.success('新增成功')
        } else {
            ElMessage.error(res.msg || '新增失败')
        }
    } catch (e) {
        ElMessage.error('新增异常')
    }
}

const editHandle = async () => {
    try {
        const res = await editActive(editId.value, buildActivityObj())
        if (res.code === '00000') {
            ElMessage.success('编辑成功')
        } else {
            ElMessage.error(res.msg || '编辑失败')
        }
    } catch (e) {
        ElMessage.error('编辑异常')
    }
}

const getVipList = async () => {
    try {
        const res = await vipEquity({
            pageNum: 1,
            pageSize: 1000,
            queryIsVip: 1
        })
        if (res.code === '00000') {
            vipData.value = res.data.list
        }
    } catch { } finally { }
}

const getEditActiveData = async () => {
    try {
        const res = await getActivityInfo(editId.value)
        if (res.code === '00000') {
            const data = res.data
            formData.activityName = data.activityName
            formData.shareImage = data.shareImage
            formData.startTime = data.startTime
            formData.endTime = data.endTime
            formData.status = data.status
            formData.title = data.title
            formData.subtitle = data.subtitle
            formData.receiveSuccessImage = data.receiveSuccessImage
            formData.activeTime = [data.startTime, data.endTime]
            if (data.activityContentAoList && data.activityContentAoList.length > 0) {
                formData.giftRefIds = data.activityContentAoList[0].giftRefIds
                    ? data.activityContentAoList[0].giftRefIds.split(',')
                    : []
                console.log(formData.giftRefIds, "===formData.giftRefIds");

            }
        }
    } catch (e) {
    } finally { }
}
onMounted(() => {
    if (route.query.id) {
        editId.value = String(route.query.id)
        getEditActiveData()
    }
    getVipList()
})

</script>
<style scoped lang="scss">
.page-content {
    width: 100%;
    height: 100%;

    .header {
        padding-bottom: 15px;
        // border-bottom: 1px solid var(--art-border-color);

        h3 {
            font-size: 18px;
            font-weight: bold;
        }
    }

    :deep(.el-form) {
        .el-form-item {
            max-width: 700px;
        }
    }
}

.tips {
    color: #333;
    font-size: 15px;
    font-weight: 500;
}

.coutomTips {
    color: #b2b4b4;
}

.check {
    color: #5f79d1;
}

:deep(.editor-wrapper) {
    z-index: 0;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;

    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 24px;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        color: #fff;
        font-size: 12px;
    }

    .del-image {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        color: #8c939d;
    }

    &:hover .mask {
        opacity: 1;
    }

    &:hover .del-image {
        display: block;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>